package unsplash;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.nio.charset.Charset;

import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONArray;

public class Api {
    private static String readAll(Reader rd) throws IOException {
        StringBuilder sb = new StringBuilder();
        int cp;
        while ((cp = rd.read()) != -1) {
            sb.append((char) cp);
        }
        return sb.toString();
    }

    public static String readStringFromUrl(String url) throws IOException {
        InputStream instream = new URL(url).openStream();
        try {
            BufferedReader rd = new BufferedReader(new InputStreamReader(instream, Charset.forName("UTF-8")));
            String jsonText = readAll(rd);
            return jsonText;
        } finally {
            instream.close();
        }
    }

    public static JSONObject readJsonObjectFromUrl(String url) throws IOException, JSONException {
        JSONObject jsonObject = new JSONObject(readStringFromUrl(url));
        return jsonObject;
    }

    public static JSONArray readJsonArrayFromUrl(String url) throws IOException, JSONException{
        JSONArray jsonArray = new JSONArray(readStringFromUrl(url));
        return jsonArray;
    }
}
